package com.s20y.register.config.es;

import java.util.List;

import com.s20y.register.config.es.mapper.IndexMapper;
import com.s20y.register.config.es.model.Trip;
import com.s20y.register.config.es.model.User;
import com.s20y.register.config.es.repository.TripRepository;
import com.s20y.register.config.es.repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * Mysql与ES同步任务
 */
@Slf4j
@Component
public class EsTasks {
    /**
     * Mysql与ES同步的间隔时间，单位分钟。默认1分钟同步一次。
     */
    private Integer intervalTime = 1;

    @Autowired
    private IndexMapper indexMapper;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private TripRepository tripRepository;

    public void updateIndex(String updateType) {
        if (updateType.equals("reload")) {
            intervalTime = 0;
        }
        List<User> users = indexMapper.selectUsers(intervalTime);
        List<Trip> trips = indexMapper.selectTrips(intervalTime);
        if (users != null && users.size() > 0) {
            userRepository.saveAll(users);
        }
        if (trips != null && trips.size() > 0) {
            tripRepository.saveAll(trips);
        }
    }

    /**
     * 默认每隔1分钟增量更新索引
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void updateLastestIndex() {
        log.info(".............................开始增量重新生成es索引任务.............................");
        this.updateIndex("updateLastest");
        log.info(".............................完成增量重新生成es索引任务.............................");
    }

    /**
     * 默认每天的1点、3点、5点全量更新索引
     */
    @Scheduled(cron = "0 0 1,3,5 * * ?}")
    public void reloadIndex() {
        log.info(".............................开始全量重新生成es索引任务.............................");
        userRepository.deleteAll();
        tripRepository.deleteAll();
        this.updateIndex("reload");
        Page<Trip> users = this.tripRepository.findBySummary("张家界", PageRequest.of(0, 10));
        log.info(".............................完成全量重新生成es索引任务.............................");
    }
}